package cn.itcast.web.controller.cargo;

import cn.afterturn.easypoi.excel.ExcelExportUtil;

import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import cn.itcast.domain.cargo.*;
import cn.itcast.service.cargo.ContractService;
import cn.itcast.service.cargo.InvoiceService;
import cn.itcast.service.cargo.PackingService;
import cn.itcast.service.cargo.ShippingService;
import cn.itcast.utils.DownloadUtil;
import cn.itcast.utils.QiniuYunUtils;
import cn.itcast.web.controller.BaseController;
import com.alibaba.dubbo.config.annotation.Reference;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


@Controller
@RequestMapping("cargo/invoice")
public class InvoiceController extends BaseController {
    @Reference
    InvoiceService invoiceService;
    @Reference
    ShippingService shippingService;//委托单
    @Reference
    PackingService packingService;//装箱单
    //报运单
    @Reference
    ContractService contractService;//购销合同


    @RequestMapping(value = "list", name = "发票管理")
    public String list(@RequestParam(defaultValue = "1") int page,
                       @RequestParam(defaultValue = "10") int size) {

        InvoiceExample invoiceExample = new InvoiceExample();
        //InvoiceExample.Criteria criteria = invoiceExample.createCriteria();


        PageInfo pageInfo = invoiceService.findAll(page, size, invoiceExample);

        request.setAttribute("page", pageInfo);
        return "cargo/invoice/invoice-list";
    }

    @RequestMapping(value = "toEdit", name = "跳转到添加的页面")
    public String toEdit(String shippingOrderId) {


        //2 贸易条款  从装箱单中获得报运合同  从合同中获得多个贸易条款
        Packing packing = packingService.findById(shippingOrderId);
        String str = packing.getExportNos();
        String[] contractArr = str.split(" ");//海关规定将多个合同号以" "的方式存储


        //前端使用,显示
        String tradeTerms = "";
        //遍历获得合同的id
        for (String contractNo : contractArr) {
            //通过id找到 合同
            ContractExample contractExample = new ContractExample();
            ContractExample.Criteria criteria = contractExample.createCriteria();
            criteria.andContractNoEqualTo(contractNo);
            List<Contract> contractList = contractService.findAll(contractExample);

            for (Contract contract : contractList) {
                //去重
                if (!tradeTerms.contains(contract.getTradeTerms())) {
                    tradeTerms += (contract.getTradeTerms() + ",");
                }
            }
        }
        //去掉最后一个逗号
        tradeTerms = tradeTerms.substring(0, tradeTerms.length() - 1);
        //回显到发票页面
        request.setAttribute("tradeTerms", tradeTerms);

        //报运合同号
        request.setAttribute("scNo", str.replace(" ", ","));

        //3发票金额
        //获得装箱金额
        request.setAttribute("invoiceMoney", packing.getPackingMoney());
        request.setAttribute("invoiceId", shippingOrderId);

        return "cargo/invoice/invoice-edit";
    }

    @RequestMapping(value = "edit", name = "将委托单保存为发票")
    public String edit(Invoice invoice, String invoiceTime, MultipartFile pickupImage) throws IOException, ParseException {

        System.out.println(invoiceTime);

        if (StringUtils.isBlank(invoice.getId())) {
            //文件保存
            if (!pickupImage.isEmpty()) {
                //获得文件的字节数组
                String url = QiniuYunUtils.upload(pickupImage.getBytes());
                //将返回值路径 保存
                invoice.setPickupPhoto(url);

            }
            //设置状态
            invoice.setStatus(0L);

            //设置时间
            Date date = new SimpleDateFormat("yyyy-MM").parse(invoiceTime);
            invoice.setInvoiceTime(date);

            //设置编码

            invoiceService.save(invoice);
        }

        return "redirect:/cargo/invoice/list.do";
    }

    @RequestMapping(value = "printExcel", name = "导出Excel")
    public String printExcel(String id, HttpServletResponse response, String invoiceTime) throws IOException {
        System.out.println(id + invoiceTime);
        String[] split = invoiceTime.split("-");
        //1定义Excel配置
        ExportParams exportParams = new ExportParams();
        exportParams.setSheetName("sheet1");//叶名称
        exportParams.setTitle(split[0] + "年" + split[1] + "月" + "合同");//大标题
        exportParams.setType(ExcelType.XSSF);//Excel版本


        //4从数据库中查找了数据
        InvoiceExample invoiceExample = new InvoiceExample();
        InvoiceExample.Criteria criteria = invoiceExample.createCriteria();
        criteria.andInvoiceIdEqualTo(id);//通过id查询发票

        List<Invoice> list = invoiceService.findAll(invoiceExample);
        List<Invoice> arrayList = new ArrayList<>();
        if (list != null && list.size() > 0) {
            for (Invoice inv : list) {
                Invoice invoiceE = new Invoice();
                invoiceE.setInvoiceId(inv.getInvoiceId());
                invoiceE.setInvoiceMoney(inv.getInvoiceMoney());
                invoiceE.setInvoiceTime(inv.getInvoiceTime());
                invoiceE.setScNo(inv.getScNo());
                invoiceE.setStatus(inv.getStatus());
                invoiceE.setTradeTerms(inv.getTradeTerms());
                //添加到集合中
                arrayList.add(invoiceE);
            }
        }

        //2创建workbook对象
        Workbook workbook = ExcelExportUtil.exportExcel(exportParams, Invoice.class, arrayList);

        //3导出到文件
        //FileOutputStream out = new FileOutputStream("D:/demo.xlsx");
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        workbook.write(byteArrayOutputStream);

        //设置时间
        DownloadUtil.download(byteArrayOutputStream, response, split[0] + "年" + split[1] + "月" + "合同.xlsx");
        workbook.close();
        return "redirect:/cargo/invoice/list.do";
    }


    @RequestMapping(value = "delete", name = "删除草稿发票")
    public String delete(String id) {


        InvoiceExample invoiceExample = new InvoiceExample();
        InvoiceExample.Criteria criteria1 = invoiceExample.createCriteria();
        criteria1.andIdEqualTo(id);
        List<Invoice> invoice = invoiceService.findAll(invoiceExample);

        String invoiceId="";
        for (Invoice invoice1 : invoice) {
            System.out.println(invoice1.getInvoiceId());
             invoiceId = invoice1.getInvoiceId();
        }

        invoiceService.delete(id);
        //删除完后修改  委托单状态
        //
        ShippingExample shippingExample = new ShippingExample();
        ShippingExample.Criteria criteria = shippingExample.createCriteria();
        criteria.andShippingOrderIdEqualTo(invoiceId);

        List<Shipping> shippingList = shippingService.findAll(shippingExample);
        for (Shipping shipping : shippingList) {
            shipping.setState(0);
            shippingService.updateByPrimaryKeySelective(shipping);
        }
        return "redirect:/cargo/invoice/list.do";
    }
}
